package com.mryang.hds.controller;

import com.mryang.hds.entity.*;
import com.mryang.hds.service.*;
import com.mryang.hds.utils.DateUtil;
import com.mryang.hds.utils.JWTUtil;
import com.mryang.hds.utils.Md5Util;
import com.mryang.hds.utils.ResultJson;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author Genius
 * @version 1.0.0
 * @ClassName ManageController.java
 * @Description TODO 管理员控制器
 * @createTime 2023年01月26日 12:50:00
 */

@RestController
@RequestMapping("/api/manage")
public class ManageController {

    @Resource
    ManageService manageService;

    @Resource
    IUserService iUserService;

    @Resource
    ITripInfoService iTripInfoService;

    @Resource
    INotifyService iNotifyService;

    @Resource
    IDeisolationService iDeisolationService;

    @Resource
    INeedService iNeedService;

    // 获取所有普通用户
    @GetMapping("/getuser")
    public ResultJson getUser(HttpServletRequest httpServletRequest) {

        // 获取管理人员所对应的用户信息
        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<User> userList = manageService.getUser(token);
        return ResultJson.success(userList);
    }

    // 获取所有医护人员
    @GetMapping("/getdocteruser")
    public ResultJson getDocterUser() {
        List<User> userList = manageService.getDocterUser();
        return ResultJson.success(userList);
    }

    // 获取所有未打卡用户
    @GetMapping("/getuserpunch")
    public ResultJson getUserNoPunch(HttpServletRequest httpServletRequest) {

        // 获取管理人员所对应的用户信息
        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<User> userList = manageService.getUserNoPunch(token);
        return ResultJson.success(userList);
    }

    // 查询用户
    @PostMapping("/searchuser")
    public ResultJson searchUser(@Param("name") String name,
                                 @Param("gender") Integer gender,
                                 @Param("age") Integer age,
                                 @Param("address") String address,
                                 HttpServletRequest httpServletRequest) {

        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<User> users = manageService.searchUser(name, gender, age, address, token);
        return ResultJson.success(users);
    }

    // 查询医护人员
    @PostMapping("/searchDocterUser")
    public ResultJson searchDocterUser(@Param("name") String name,
                                       @Param("gender") Integer gender,
                                       @Param("age") Integer age,
                                       @Param("address") String address) {

        List<User> users = manageService.searchDocterUser(name, gender, age, address);
        return ResultJson.success(users);
    }


    // 打卡情况查询
    @PostMapping("/searchpunch")
    public ResultJson searchPunch(@Param("name") String name,
                                  @Param("status") Integer status,
                                  @Param("punchInfo") Integer punchInfo,
                                  @Param("address") String address,
                                  HttpServletRequest httpServletRequest) {
        // 获取管理人员所对应的用户信息
        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));


        List<User> users = manageService.searchPunch(name, status, punchInfo, address, token);
        return ResultJson.success(users);
    }

    // 删除选择用户数据
    @DeleteMapping("/delUser")
    public ResultJson delUser(@Param("userId") Integer userId) {

        manageService.delUser(userId);
        return ResultJson.success("删除成功！");
    }


    // 获取用户数据
    @PostMapping("/getuserbyid")
    public ResultJson getUserById(@Param("userId") Integer userId) {

        User user = manageService.getUserById(userId);

        // System.out.println(userId);
        return ResultJson.success(user);
    }

    // 添加用户
    @PostMapping("/adduser")
    public ResultJson addUser(User user) {

        // 设置默认密码为身份证后6位
        String idCard = user.getIdCard();

        // 对用户注册 密码使用 MD5加密
        user.setPassword(Md5Util.encode(idCard.substring(idCard.length() - 6)));

        iUserService.addUser(user);

        // System.out.println(user);
        return ResultJson.success("用户添加成功，等待管理员分配用户！");
    }

    // 修改用户
    @PostMapping("/edituserbyid")
    public ResultJson editUser(User user) {

        System.out.println(user);

        // 查找用户原始数据信息
        User userOld = iUserService.getUserById(user.getUserId());


        iUserService.editUser(user, userOld);

        return ResultJson.success("用户修改成功");
    }

    // 重置用户密码为身份证后6位
    @PostMapping("/editupwd")
    public ResultJson editUPWD(@Param("userId") Integer userId, @Param("idCard") String idCard) {
        // 对密码加密
        String newPWD = Md5Util.encode(idCard.substring(idCard.length() - 6));

        iUserService.updatePwd(userId, newPWD);

        return ResultJson.success("用户密码重置成功");
    }


    // 根据创建人获取用户信息
    @GetMapping("/getubycreator")
    public ResultJson getUByCreator(@Param("createId") String createId) {
        List<User> uByCreator = iUserService.getUByCreator(createId);
        return ResultJson.success(uByCreator, "用户信息查询成功");
    }

    // 批量重置用户打卡状态为 未打卡
    @PutMapping("/editPunchInfoAll")
    public ResultJson editPunchInfoAll(){

        manageService.editPunchInfoAll();

        return ResultJson.success("批量重置成功");
    }

    // 批量删除所有用户 14天前的 打卡记录
    @PutMapping("/deletePunchInfoAll")
    public ResultJson deletePunchInfoAll(){

        manageService.deletePunchInfoAll();

        return ResultJson.success("批量删除成功");
    }

//----------------------------------用户分配操作------------------------------

    @GetMapping("/assm/getassmuser")
    public ResultJson getAssmUser(@Param("createOk") Integer createOk) {
        List<User> assmUser = iUserService.getAssmUser(createOk);
        return ResultJson.success(assmUser, "用户信息查询成功");
    }

    @PostMapping("/assm/editselectsuser")
    public ResultJson editSelectsUser(@RequestParam List<Integer> selectsId,
                                      @RequestParam String createId) {
        iUserService.editSelectsUser(selectsId,createId);
        return ResultJson.success("用户分配成功");
    }

    @PostMapping("/assm/searchnoassm")
    public ResultJson searchNoAssm(String name,
                                   Integer createOk,
                                   String address) {
        List<User> users = iUserService.searchNoAssm(name, createOk, address);
        return ResultJson.success(users,"用户检索成功");
    }


    //----------------------------------解除隔离审核------------------------------

    // 检索
    @PostMapping("/deisolation/searchDIS")
    public ResultJson searchDIS(String searchFlag,String input,HttpServletRequest httpServletRequest){


        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<Recovered> recovereds = iDeisolationService.searchDIS(searchFlag, input, token);


        return ResultJson.success(recovereds,"数据检索成功");
    }

    // 获取所有待审核的用户
    @GetMapping("/deisolation/getDLUsers")
    public ResultJson getDLUsers(HttpServletRequest httpServletRequest){
        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<Recovered> dlUsers = iDeisolationService.getDLUsers(token);

        return ResultJson.success(dlUsers,"申请提交成功");
    }


    /**
     * 查询指定用户的相关打卡信息
     * @param userId 用户编号
     * @return 相关信息
     */
    @GetMapping("/deisolation/gethealthinfo")
    public ResultJson getHealthInfo(Integer userId){
        Temp healthInfo = iDeisolationService.getHealthInfo(userId);

        return ResultJson.success(healthInfo);
    }

    // 审核通过与否
    @PostMapping("/deisolation/checkdtuser")
    public ResultJson checkDTUser(Integer recoveredId,Boolean checked,Integer userId,HttpServletRequest httpServletRequest){

        Integer auditId = JWTUtil.getTokenInfoIndex(httpServletRequest.getHeader("token"));

        iDeisolationService.checkDTUser(recoveredId,checked,userId,auditId);
        return ResultJson.success("审核成功");
    }

//----------------------------------当日打卡操作------------------------------

    // 打卡信息驳回
    @PostMapping("/delSelectId")
    public ResultJson delSelect(@RequestBody List<Integer> selectId) {

        manageService.delSelect(selectId);
        return ResultJson.success("打卡信息驳回成功！");
    }


    // 未打卡用户批量记录
    @PostMapping("/noPunchUAdd")
    public ResultJson noPunchUAdd(@RequestBody List<Integer> selectId,HttpServletRequest httpServletRequest){

        Integer loginId = JWTUtil.getTokenInfoIndex(httpServletRequest.getHeader("token"));
        int i = manageService.noPunchUAdd(selectId, loginId);

        if (i != 0){
            return ResultJson.error("部分未打卡用户已进行记录,请勿对此类用户进行重复操作！");
        }

        return ResultJson.success("未打卡用户批量记录成功！");

    }





//----------------------------------往日打卡操作------------------------------

    //检索
    @PostMapping("/searchpunchpast")
    public ResultJson searchPunchPast(PunchRecord punchRecord, HttpServletRequest httpServletRequest) {

        // System.out.println(punchRecord);

        // 获取管理人员所对应的用户信息
        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<PunchRecord> users = manageService.searchPunchPast(punchRecord, token);
        return ResultJson.success(users, "数据检索成功");
    }

    // 获取最近所有打卡信息
    @GetMapping("/getpunchtable")
    public ResultJson getPunchTable(HttpServletRequest httpServletRequest) {

        // 获取管理人员所对应的用户信息
        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<PunchRecord> punchRecords = manageService.getPunchTable(token);
        return ResultJson.success(punchRecords, "数据检索成功");
    }

    // 通过id获取用户打卡信息
    @GetMapping("/getpunchpastbyid")
    public ResultJson getPunchPastById(@Param("userId") Integer userId) {

        List<PunchRecord> punchRecords = manageService.getPunchPastById(userId);
        return ResultJson.success(punchRecords, "数据检索成功");
    }

    // 通过用户编号和时间 获取用户打卡内容
    @GetMapping("/getpunchinfobyidandtime")
    public ResultJson getPunchInfoByIdAndTime(@Param("userId") Integer userId, @Param("punchTime") String punchTime) {

        List<PunchInfo> punchRecords = manageService.getPunchInfoByIdAndTime(userId, punchTime);

        return ResultJson.success(punchRecords, "数据检索成功");
    }


//----------------------------------需求相关操作------------------------------

    // 查询 待/已 审核数据
    @GetMapping("/need/auditingneed")
    public ResultJson needAuditing(@Param("needState") Integer needState, HttpServletRequest httpServletRequest) {

        Integer userId = JWTUtil.getTokenInfoIndex(httpServletRequest.getHeader("token"));
        // System.out.println(needState);
        // System.out.println(userId);

        List<Need> needs = manageService.needAuditing(needState, userId);
        // System.out.println(needs.get(0));

        return ResultJson.success(needs, "审核数据查询成功");
    }

    // 审核
    @PostMapping("/need/auditingneedbyid")
    public ResultJson needAuditingById(Need need) {

        manageService.needAuditingById(need.getNeedId(), need.getNeedState(), need.getNeedRemark());

        return ResultJson.success("审核数据成功");
    }

    // 获取所有数据
    @GetMapping("/need/getneedtabledata")
    public ResultJson getNeedTableData(HttpServletRequest httpServletRequest) {

        Integer status = JWTUtil.getTokenFlag(httpServletRequest.getHeader("token"));
        Integer userId = JWTUtil.getTokenInfoIndex(httpServletRequest.getHeader("token"));

        List<Need> needData = manageService.getNeedData(status, userId);

        return ResultJson.success(needData);
    }

    // 需求检索
    @PostMapping("/need/search")
    public ResultJson needSearch(@Param("title") String title,
                                 @Param("state") Integer state,
                                 @Param("start") String start,
                                 @Param("end") String end,
                                 HttpServletRequest httpServletRequest) {

        User tokenuser = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<Need> users = manageService.needSearch(title, state, start, end, tokenuser);
        return ResultJson.success(users);
    }

    @PostMapping("/need/needdatastateupd")
    public ResultJson needDataStateUpd(@Param("needState") Integer needState, @Param("needId") Integer needId) {

        manageService.needDataStateUpd(needState, needId);
        if (needState == 2) {
            return ResultJson.error("不能对派送中的需求进行操作！");
        }

        return ResultJson.success("驳回成功");

    }

    @PostMapping("/need/needdataupd")
    public ResultJson needDataUpd(@Param("need") Need need) {

        manageService.needDataUpd(need);

        return ResultJson.success("编辑成功");

    }

    // 删除需求
    @DeleteMapping("/need/delbyid/{needId}")
    public ResultJson<Object> deleteNeed(@PathVariable Integer needId) {

        // System.out.println(needId);

        iNeedService.deleteNeed(needId);

        return ResultJson.success("需求删除成功");
    }


//----------------------------------通知相关操作------------------------------

    @GetMapping("/ask/tags")
    public ResultJson getUserSelectTags(@Param("selectedTagUser") Integer selectedTagUser, @Param("selectedTagDoc") Integer selectedTagDoc) {


        List<List<User>> SelectTags = manageService.getUserSelectTags(selectedTagUser, selectedTagDoc);

        return ResultJson.success(SelectTags);

    }

    @PostMapping("/ask/asksub")
    public ResultJson askSub(@Param("notify") Notify notify, HttpServletRequest httpServletRequest) {

        // System.out.println(notify);

        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        String createTime = DateUtil.dateToString(new Date(), null);
        // notify.setCreateId(token.getUserId());

        notify.setCreateTime(createTime);


        if (token.getStatus() == 1) { // 普通用户提交消息：消息创建人：用户、消息被通知人：用户的创建人
            User userById = iUserService.getUserById(token.getUserId());
            notify.setUserId(Integer.parseInt(userById.getCreateId()));
            notify.setCreateId(token.getUserId());
        } else {
            notify.setCreateId(token.getUserId());
        }

        manageService.askSub(notify);

        return ResultJson.success("消息已通知");

    }


//----------------------------------行程相关操作------------------------------

    @GetMapping("/trips")
    public ResultJson getTrips(HttpServletRequest httpServletRequest) {

        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<TripInfo> trips = iTripInfoService.getTrips(token);

        // System.out.println(trips.get(0));
        return ResultJson.success(trips);
    }

    @PostMapping("/trip/addtrip")
    public ResultJson addTrip(@Param("tripInfo") TripInfo tripInfo) {

        // System.out.println(tripInfo);

        String tripSub = DateUtil.dateToString(new Date(), null);
        tripInfo.setSubTime(tripSub);

        iTripInfoService.addTrip(tripInfo);

        return ResultJson.success("行程添加成功");
    }

    @PostMapping("/trip/edittrip")
    public ResultJson editTrip(@Param("tripInfo") TripInfo tripInfo) {

        // System.out.println(tripInfo);

        // String tripSub = DateUtil.dateToString(new Date(), null);
        // tripInfo.setSubTime(tripSub);

        iTripInfoService.editTrip(tripInfo);

        return ResultJson.success("行程信息修改成功");
    }

    @DeleteMapping("/trip/deletetrip/{tid}")
    public ResultJson<Object> deleteResource(@PathVariable Integer tid) {

        // System.out.println(tid);

        iTripInfoService.deleteTrip(tid);

        return ResultJson.success("行程信息删除成功");
    }


    //----------------------------------消息相关操作------------------------------
    // 根据创建者查找消息
    @GetMapping("/notify/getnotifys")
    public ResultJson getNotifys(HttpServletRequest httpServletRequest) {
        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));
        List<Notify> notifys = iNotifyService.getNotifys(token);

        return ResultJson.success(notifys, "数据检索成功");
    }

    // 修改消息
    @PostMapping("/notify/editbyid")
    public ResultJson editById(Notify notify, HttpServletRequest httpServletRequest) {
        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        notify.setCreateId(token.getUserId());
        notify.setCreatestatus(token.getStatus());
        System.out.println(notify);

        iNotifyService.editById(notify);

        return ResultJson.success("数据修改成功");
    }

    @DeleteMapping("/notify/deletenotify/{nid}")
    public ResultJson<Object> deleteNotify(@PathVariable Integer nid) {

        // System.out.println(tid);

        iNotifyService.deleteNotify(nid);

        return ResultJson.success("通知删除成功");
    }

    // 检索消息
    @PostMapping("/notify/searchnotify")
    public ResultJson searchNotify(Notify notify, HttpServletRequest httpServletRequest) {
        System.out.println(notify);

        User token = JWTUtil.getTokenMap(httpServletRequest.getHeader("token"));

        List<Notify> notifies = iNotifyService.searchNotify(notify, token);

        return ResultJson.success(notifies, "消息检索成功！");
    }


}
